package com.ecut.drug_bid.service;

import com.ecut.drug_bid.domain.Tender;
import com.ecut.drug_bid.dto.TenderCreateRequest;
import com.ecut.drug_bid.repository.TenderRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class TenderService {

    private final TenderRepository tenderRepository;

    // 查询所有招标信息
    public List<Tender> findAll() {
        return tenderRepository.findAll();
    }

    // 根据编号查询
    public Optional<Tender> findByCode(String tenderCode) {
        return tenderRepository.findById(tenderCode);
    }

    // 创建招标（仅招标单位和管理员）
    @Transactional
    public Tender create(TenderCreateRequest request, Long userId) {
        // 检查编号是否已存在
        if (tenderRepository.existsById(request.getTenderCode())) {
            throw new RuntimeException("招标项目编号已存在");
        }

        Tender tender = new Tender();
        tender.setTenderCode(request.getTenderCode());
        tender.setDrugName(request.getDrugName());
        tender.setManufacturer(request.getManufacturer());
        tender.setPackageReq(request.getPackageReq());
        tender.setTotalAmount(request.getTotalAmount());
        tender.setDeadline(request.getDeadline());
        tender.setDeposit(request.getDeposit());
        tender.setCreatedBy(userId);
        tender.setCreatedAt(LocalDateTime.now());
        tender.setUpdatedAt(LocalDateTime.now());

        return tenderRepository.save(tender);
    }

    // 更新招标（仅招标单位和管理员）
    @Transactional
    public Tender update(String tenderCode, TenderCreateRequest request, Long userId) {
        Tender tender = tenderRepository.findById(tenderCode)
            .orElseThrow(() -> new RuntimeException("招标信息不存在"));

        tender.setDrugName(request.getDrugName());
        tender.setManufacturer(request.getManufacturer());
        tender.setPackageReq(request.getPackageReq());
        tender.setTotalAmount(request.getTotalAmount());
        tender.setDeadline(request.getDeadline());
        tender.setDeposit(request.getDeposit());
        tender.setUpdatedAt(LocalDateTime.now());

        return tenderRepository.save(tender);
    }

    // 删除招标（仅管理员）
    @Transactional
    public void delete(String tenderCode) {
        if (!tenderRepository.existsById(tenderCode)) {
            throw new RuntimeException("招标信息不存在");
        }
        tenderRepository.deleteById(tenderCode);
    }
}